package cn.gem.rainbow.other;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class OtherApi {

    @ResponseBody
    @GetMapping(path = "str")
    public String strRsp() {
        return "hello " + UUID.randomUUID().toString();
    }

    @ResponseBody
    @GetMapping(path = "str2")
    public void strRsp2(HttpServletResponse response) throws IOException {
        Map<String, String> ans = new HashMap<>(2);
        ans.put("a", "b");
        ans.put("b", "c");
        response.getOutputStream().write(JSON.toJSONString(ans).getBytes());
        response.getOutputStream().flush();
    }

    /**
     * 返回数组
     *
     * @return
     */
    @ResponseBody
    @GetMapping(path = "ary3")
    public String[] aryRsp() {
        return new String[]{UUID.randomUUID().toString(), LocalDateTime.now().toString()};
    }

    @ResponseBody
    @GetMapping(path = "html")
    public String strHtmlRsp() {
        return "<html>\n" + "<head>\n" + "    <title>返回数据测试</title>\n" + "</head>\n" + "<body>\n" +
                "<h1>欢迎欢迎，热烈欢迎</h1>\n" + "</body>\n" + "</html>";
    }

    /**
     * 返回视图
     *
     * @return
     */
    @RequiresPermissions("login")
    @GetMapping(path = "view2")
    public String viewRsp() {
        return "view2";
    }


    /**
     * 返回图片
     */
    @GetMapping(path = "img")
    public void imgRsp(HttpServletResponse response) throws IOException {
        response.setContentType("image/png");
        ServletOutputStream outStream = response.getOutputStream();

        String path = "https://spring.hhui.top/spring-blog/imgs/info/info.png";
        URL uri = new URL(path);
        BufferedImage img = ImageIO.read(uri);
        ImageIO.write(img, "png", response.getOutputStream());
        System.out.println("--------");
    }

}
